package com.zhida.smartcontrol.mvp;

import android.content.Context;

import com.dyhdyh.widget.loadingbar2.LoadingBar;
import com.zhida.smartcontrol.mvp.permisson.PermissionCheckerFragment;
import com.zhida.smartcontrol.utils.CustomDialogFactory;

import java.lang.reflect.ParameterizedType;

/**
 * author: tanjianpei
 * date: 2019/8/19 019 15:10
 * description:
 */
public abstract class MVPBaseFragment<V extends BaseView, T extends BasePresenterImpl<V>> extends PermissionCheckerFragment implements BaseView {
    protected T mPresenter;

    @Override
    protected void initPresenter() {
        mPresenter = getInstance(this, 1);
        mPresenter.attachView((V) this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LoadingBar.release();
        if (mPresenter != null)
            mPresenter.detachView();
    }

    @Override
    public Context getContext() {
        return super.getContext();
    }

    @Override
    public void showLoading(String msg) {
        LoadingBar.dialog(getProxyActivity())
                //通过工厂设置样式
                .setFactory(new CustomDialogFactory(msg))
                //通过View设置样式
                //.setFactoryFromView(view)
                //通过布局ID设置样式
//                .setFactoryFromResource(R.layout.layout_loading)
                //携带参数
                .extras(new Object[]{})
                .show();
    }

    @Override
    public void hideLoading() {
        LoadingBar.dialog(getProxyActivity()).cancel();
    }

    @Override
    public void showMsg(String msg) {
        toast(msg);
    }

    @Override
    protected void noPermission() {
        showTipsDialog(this);
    }

    public <T> T getInstance(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass()
                    .getGenericSuperclass())).getActualTypeArguments()[i])
                    .newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
